package com.tengju.bff.application.wx;

import com.tengju.bff.domain.shared.JsonUtil;
import com.tengju.data.domain.model.wx.WxUserInfo;
import com.tengju.data.domain.model.wx.WxUserInfoRepository;
import com.tengju.support.domain.model.wx.DepartmentId;
import com.tengju.support.domain.model.wx.WechatSimpleUserInfo;
import com.tengju.support.domain.service.WeiXinCompanyService;
import com.tengju.support.domain.shared.IdObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.tengju.support.domain.model.wx.FetchChild.WITH_SUB_DEPARTMENT;

/**
 * @author: 李大仙
 * @date: 2021/11/25 4:43 下午
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class WxUserDiffJobService {

    private final WxUserInfoRepository wxUserInfoRepository;
    private final WeiXinCompanyService weiXinCompanyService;

    @Value("${weixin.work.user.root.department.id}")
    private String weixinRootDepartmentIdStr;
    @Value("${weixin.work.user.invalid.department.id}")
    private String weixinInvalidDepartmentIdStr;

    public void execute() {
        // 获取数据库内数据
        List<WxUserInfo> localUserInfoList = wxUserInfoRepository.selectAll();
        List<String> localUserIdCodeList = localUserInfoList.stream()
                .map(l -> l.getIdCode().toString()).collect(Collectors.toList());

        // 获取企业微信数据
        List<WechatSimpleUserInfo> wxUserInfoList = weiXinCompanyService.getUserByDepartment(new DepartmentId(Long.parseLong(weixinRootDepartmentIdStr)), WITH_SUB_DEPARTMENT);
        List<String> wxUserIdCodeList = wxUserInfoList.stream()
                .filter(w -> !w.getDepartmentIds().stream().map(IdObject::toString).collect(Collectors.toList()).contains(weixinInvalidDepartmentIdStr))
                .map(WechatSimpleUserInfo::getUserId).collect(Collectors.toList());

        List<String> wxLost = new ArrayList<>();
        List<String> localLost = new ArrayList<>();
        for (String localUserIdCode : localUserIdCodeList) {
            if (!wxUserIdCodeList.contains(localUserIdCode)) {
                wxLost.add(localUserIdCode);
            }
        }

        for (String wxUserIdCode : wxUserIdCodeList) {
            if (!localUserIdCodeList.contains(wxUserIdCode)) {
                localLost.add(wxUserIdCode);
            }
        }

        log.info("wx count: {}, wxLost lost : {}", wxUserIdCodeList.size(), JsonUtil.toJSONString(wxLost));
        log.info("local count: {}, localLost lost : {}", localUserIdCodeList.size(), JsonUtil.toJSONString(localLost));
    }
}
